import axios from 'axios'
import APIUrl from './api.url'
import md5 from 'js-md5'

// 默认配置
axios.defaults.timeout = 5000 // 超时时间为5秒
axios.defaults.baseURL = APIUrl.domain
axios.defaults.responseType = 'json'
axios.defaults.headers.common = {
  'Content-Type': 'application/json;charset=UTF-8',
  'Accept': 'application/json',
  'X-Timestamp': 0
}
axios.defaults.withCredentials = false

axios.interceptors.request.use(
  config => {
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

axios.interceptors.response.use(
  response => {
    switch (response.data.code) {
      case 20001:
        response.data.message = '请登录'
        break
      default:
    }
    return response
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

export default axios

export function addHeader (key, value) {
  axios.defaults.headers.common[key] = value
}

/**
 * 本地永久存储封装, 添加有效期
 * @param key
 * @param value
 * @param expireTime 有效时间，到秒, 不传或传0为永久
 * @return {*}
 */
export function storage (key, value = null, expireTime = null) {
  key = 'srm-' + key
  if (value !== null) {
    value = {
      data: value,
      expire: expireTime ? getTimestamp() + expireTime : 0
    }
    localStorage.setItem(key, JSON.stringify(value))
    return true
  } else {
    let item = localStorage.getItem(key)
    if (item) {
      item = JSON.parse(item)
      // 是否已过期
      if (item.expire && item.expire <= getTimestamp()) {
        item.data = ''
        // 已过期，设置为空
        storage(key, '')
      }
      return item.data
    } else {
      return ''
    }
  }
}

/**
 * 获取用户TOKEN
 * @param value
 * @return {*}
 */
export function token (value = null) {
  return storage('user-token', value, 86400 * 7)
}

export function objectSort (params = {}) {
  for (let i = 0; i < params.length - 1; i++) {
    for (let j = 0; j < params.length - 1 - i; j++) {
      if (params[j] > params[j + 1]) {
        let temp = params[j]
        params[j] = params[j + 1]
        params[j + 1] = temp
      }
    }
  }
  return params
}

export function getSecret () {
  return '70104f708b2d52bf40'
}

export function getTimestamp () {
  return parseInt(Date.parse(new Date()) / 1000)
}

export function sign (arr, timestamp) {
  let keys = []
  let i = 0
  if (arr) {
    for (let key in arr) {
      keys[i] = key
      i++
    }
  }
  keys = objectSort(keys)
  let signString = ''
  for (let j = 0; j < keys.length; j++) {
    signString += '&' + keys[j] + '=' + arr[keys[j]]
  }
  signString = signString.substr(1)
  signString += (signString ? '&' : '') + 'secret=' + getSecret() + '&timestamp=' + timestamp
  return md5(signString)
}
